const router = require("koa-router")();
const DB = require("../../module/db");
const tools = require("../../module/tools");
// const bodyParser = require('koa-bodyparser');
const multer = require("koa-multer");

/* 文件上传模块的配置 */
var storage = multer.diskStorage({
  // 文件保存路径
  destination: function (req, file, cb) {
    cb(null, "public/upload"); // 配置图片上传的目录  注意：图片上传的目录必须存在
  },
  // 文件名称的设置
  filename: function (req, file, cb) {
    var fileFormat = (file.originalname).split(".");
    cb(null, Date.now() + "." + fileFormat[fileFormat.length - 1]);
  },
});
var upload = multer({ storage: storage });


// 显示列表展示页面
router.get("/", async (ctx) => {
  let page = ctx.query.page || 1;
  let pageSize = 8;
  let res = await DB.find("article", {}, {}, pageSize, page, {'add_time': -1});
  let totleNum = await DB.count("article", {});
  let totlePages = Math.ceil(totleNum / pageSize);
  await ctx.render("admin/article/list.html", {
    list: res,
    totleNum,
    pageSize,
    page,
    totlePages,
  });
});

// 显示添加页面
router.get("/addArticle", async (ctx) => {
  //查询分类数据
  var catelist=await DB.find('articlecate',{});

  console.log(`数据库查询的分类视据：${tools.getArticleData(catelist)}`);

  await  ctx.render('admin/article/add.html',{
      catelist:tools.getArticleData(catelist)
  });
});

// 提交添加数据
router.post("/doAddArticle", upload.single('img_url'), async (ctx) => {
  let pid=ctx.req.body.pid;
    let catename=ctx.req.body.catename.trim();
    let title=ctx.req.body.title.trim();
    let author=ctx.req.body.author.trim();
    let pic=ctx.req.body.author;
    let status=ctx.req.body.status;
    let is_best=ctx.req.body.is_best;
    let is_hot=ctx.req.body.is_hot;
    let is_new=ctx.req.body.is_new;
    let keywords=ctx.req.body.keywords;
    let description=ctx.req.body.description || '';
    let content=ctx.req.body.content ||'';
    let img_url=ctx.req.file? ctx.req.file.path.substr(7) :'';

    let add_time=tools.getTime();

    //console.log(img_url);
    //属性的简写
    let json={
        pid,catename,title,author,status,is_best,is_hot,is_new,keywords,description,content,img_url,add_time
    }

    var result=DB.insert('article',json);

    //跳转
    ctx.redirect(ctx.state.__HOST__+'/admin/article');
})

router.get('/edit',async (ctx)=>{

  //查询分类数据
  var id=ctx.query.id;
  //分类
  var catelist=await DB.find('articlecate',{});
  //当前要编辑的数据
  var articlelist=await DB.find('article',{"_id":DB.getObjectId(id)});
  await  ctx.render('admin/article/edit',{
      catelist:tools.getArticleData(catelist),
      list:articlelist[0],
      prevPage :ctx.state.G.prevPage   /*保存上一页的值*/
  });

})

router.post('/doEdit', upload.single('img_url'),async (ctx)=>{

  let prevPage=ctx.req.body.prevPage || '';  /*上一页的地址*/
  let id=ctx.req.body.id;
  let pid=ctx.req.body.pid;
  let catename=ctx.req.body.catename.trim();
  let title=ctx.req.body.title.trim();
  let author=ctx.req.body.author.trim();
  let pic=ctx.req.body.author;
  let status=ctx.req.body.status;
  let is_best=ctx.req.body.is_best;
  let is_hot=ctx.req.body.is_hot;
  let is_new=ctx.req.body.is_new;
  let keywords=ctx.req.body.keywords;
  let description=ctx.req.body.description || '';
  let content=ctx.req.body.content ||'';
  let img_url=ctx.req.file? ctx.req.file.path.substr(7) :'';
  //属性的简写
  //注意是否修改了图片          var           let块作用域
  if(img_url){
      var json={
          pid,catename,title,author,status,is_best,is_hot,is_new,keywords,description,content,img_url
      }
  }else{
      var json={
          pid,catename,title,author,status,is_best,is_hot,is_new,keywords,description,content
      }
  }

  DB.update('article',{"_id":DB.getObjectId(id)},json);


  //跳转
  if(prevPage){
      ctx.redirect(prevPage);

  }else{
      ctx.redirect(ctx.state.__HOST__+'/admin/article');
  }


})

module.exports = router.routes();
